
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status

from user.models import *
from user.serializers import *
from .serializer import *
from user.utils import jwt_auth

import json

# 流程管理
class FlowView(ViewSet):

    @jwt_auth
    # 获取所有流程
    def flowshow(self, request):

        try:
            stations = StationModel.objects.filter(id=self._cuser.stations_id, is_delete=False).first()
            sections = SectionModel.objects.filter(id=stations.sections_id).first()
            flow = FlowModel.objects.filter(sections_id=sections.id,  is_delete=False).all()
            ser = FlowSer(flow, many=True)
            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':ser.data})
        except Exception as e:
            print(str(e))
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':'服务器错误'})

    @jwt_auth
    # 获取流程详情
    def flow_desc(self, request, pk):

        try:
            flow = FlowModel.objects.filter(id=pk, is_delete=False).first()
            ser = FlowSer(flow)
            flow = json.loads(json.dumps(ser.data))

            node = FlowNodeModel.objects.filter(flows_id=flow['id'], nodes=None).all()
            node = FlowNodeSer(node, many=True)
            node = json.loads(json.dumps(node.data))
            for i in node:
                type = NodeTypeModel.objects.filter(nodes_id=i['id']).all()
                type = NodeTypeSer(type, many=True)
                type = json.loads(json.dumps(type.data))
                i['type_list'] = type
                for j in type:
                    content = FlowContentModel.objects.filter(type_id=j['id']).all()
                    content = FlowContentSer(content, many=True)
                    content = json.loads(json.dumps(content.data))
                    j['content_list'] = content
            flow["node_list"] = node
            return Response({'code': status.HTTP_200_OK,'msg': '获取成功', 'data': flow})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':'服务器错误'})

    @jwt_auth
    # 添加流程
    def add_flow(self, request):
        # 流程
        flows = request.data.get('flows')
        sections = request.data.get('sections')
        # 第一个节点
        node1 = request.data.get('node1')
        station1 = request.data.get('station1')
        # 第一个节点类型
        title1 = request.data.get('title1')
        # 第二个节点类型
        title2 = request.data.get('title2')
        # 第三个节点类型
        title3 = request.data.get('title3')
        # 第四个节点类型
        title4 = request.data.get('title4')
        # 第二个节点
        node2 = request.data.get('node2')
        station2 = request.data.get('station2')
        # 第三个节点
        node3 = request.data.get('node3')
        station3 = request.data.get('station3')

        try:
            # 添加流程
            section = SectionModel.objects.filter(name=sections, is_delete=False).first()
            flag = FlowModel.objects.filter(name=flows, sections_id=section.id).first()
            if flag:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该流程已存在'})
            FlowModel.objects.create(name=flows, sections_id=section.id)

            # 添加节点
            flow = FlowModel.objects.filter(name=flows, sections_id=section.id).first()
            stations1 = StationModel.objects.filter(name=station1).first()
            FlowNodeModel.objects.create(name=node1, stations_id=stations1.id, flows_id=flow.id, nodes=None)

            # 添加节点类型
            nodes1 = FlowNodeModel.objects.filter(name=node1, stations_id=stations1.id, flows_id=flow.id, nodes=None).first()
            NodeTypeModel.objects.create(title=title1,nodes_id=nodes1.id)

            # 添加第二个节点类型
            if title2:
                NodeTypeModel.objects.create(title=title2, nodes_id=nodes1.id)

            # 添加第三个节点类型
            if title3:
                NodeTypeModel.objects.create(title=title3, nodes_id=nodes1.id)

            # 添加第四个节点类型
            if title4:
                NodeTypeModel.objects.create(title=title4, nodes_id=nodes1.ic)

            # 添加第二个节点
            if (node2) and (station2):
                stations2 = StationModel.objects.filter(name=station2).first()
                FlowNodeModel.objects.create(name=node2, stations_id=stations2.id, nodes=nodes1.id, flows_id=flow.id)

            # 添加第三个节点
            if (node3) and (station3):
                stations3 = StationModel.objects.filter(name=station3).first()
                nodes2 = FlowNodeModel.objects.filter(name=node2, stations_id=stations2.id, nodes=nodes1.id).first()
                FlowNodeModel.objects.create(name=node3, stations_id=stations3.id, flows_id=flow.id, nodes=nodes2.id)

            return Response({'code':status.HTTP_200_OK,'msg':'添加成功'})
        except Exception as e:
            print(str(e))
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':'服务器错误'})

    @jwt_auth
    # 获取部门下的职位
    def section_desc(self, request):

        sections = request.data.get('sections')
        try:
            section = SectionModel.objects.filter(name=sections).first()
            stations = StationModel.objects.filter(sections_id=section.id).all()
            stations = StationSer(stations, many=True)

            return Response({'code': status.HTTP_200_OK, 'msg': '获取成功','data':stations.data})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})

    @jwt_auth
    # 删除流程
    def del_flow(self, request, pk):

        try:
            flag = FlowModel.objects.filter(id=pk).first()
            if not flag:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该流程不存在'})

            flag = HistoryModel.objects.filter(flows_id=pk, is_status=1).count()
            if flag != 0:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "该流程下有流程正在审批中！"})

            FlowModel.objects.filter(id=pk).update(is_delete=True)
            return Response({'code':status.HTTP_200_OK,'msg':'删除成功'})
        except Exception as e:
            print(str(e))
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':'服务器错误'})

# 审批流程
class HistoryView(ViewSet):

    @jwt_auth
    # 获取该用户申请的流程实例
    def historyshow(self, request):
        try:
            history = HistoryModel.objects.filter(users_id=self._cuser.id).all()
            print(history)
            ser = HistorySer(history, many=True)

            return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': ser.data})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})

    @jwt_auth
    # 获取实例详情
    def history_desc(self, request, pk):
        try:
            history = HistoryModel.objects.filter(id=pk, users_id=self._cuser.id).first()
            history = HistorySer(history)
            history = json.loads(json.dumps(history.data))
            flow = FlowModel.objects.filter(id=history['flows']).first()
            flow = FlowSer(flow)
            flow = json.loads(json.dumps(flow.data))
            node = FlowNodeModel.objects.filter(flows_id=flow['id']).all()
            node = FlowNodeSer(node, many=True)
            node = json.loads(json.dumps(node.data))
            for i in node:
                type = NodeTypeModel.objects.filter(nodes_id=i['id']).all()
                type = NodeTypeSer(type, many=True)
                type = json.loads(json.dumps(type.data))
                i['type_list'] = type
                for i in type:
                    content = FlowContentModel.objects.filter(type_id=i['id']).all()
                    content = FlowContentSer(content, many=True)
                    content = json.loads(json.dumps(content.data))
                    i['content_list'] = content
            history['node_list'] = node
            return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': history})
        except Exception as e:
            print("错误信息", e)
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})

    @jwt_auth
    # 获取该用户审批的节点实例
    def approvalshow(self, request):
        try:

            stations = StationModel.objects.filter(id=self._cuser.stations_id).first()
            approval = ApprovalModel.objects.filter(stations_id=stations.id).all()
            ser = ApprovalSer(approval, many=True)
            return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': ser.data})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})

    @jwt_auth
    # 获取节点内容类型
    def node_type(self, request):
        flows = request.data.get('flows')

        try:
            flow = FlowModel.objects.filter(name=flows, is_delete=False).first()
            node = FlowNodeModel.objects.filter(flows_id=flow.id, nodes=None).first()
            type = NodeTypeModel.objects.filter(nodes_id=node.id).all()
            ser = NodeTypeSer(type, many=True)
            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':ser.data})
        except Exception as e:
            print(str(e))
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':'服务器错误'})

    @jwt_auth
    # 添加审批流程
    def add_history(self,request):
        flows = request.data.get('flows')
        title1 = request.data.get('title1')
        title2 = request.data.get('title2')
        title3 = request.data.get('title3')
        title4 = request.data.get('title4')
        content1 = request.data.get('content1')
        content2 = request.data.get('content2')
        content3 = request.data.get('content2')
        content4 = request.data.get('content3')

        try:
            # 添加第一个节点内容
            titles1 = NodeTypeModel.objects.filter(title=title1, is_delete=False).first()
            FlowContentModel.objects.create(name=content1, type_id=titles1.id)

            if (title2) and (content2):
                # 添加第二个节点内容
                titles2 = NodeTypeModel.objects.filter(title=title2, is_delete=False).first()
                FlowContentModel.objects.create(name=content2, type_id=titles2.id)

            if (title3) and (content3):
                # 添加第三个节点内容
                titles3 = NodeTypeModel.objects.filter(title=title3, is_delete=False).first()
                FlowContentModel.objects.create(name=content3, type_id=titles3.id)

            if (title4) and (content4):
                # 添加第四个节点内容
                titles4 = NodeTypeModel.objects.filter(title=title4, is_delete=False).first()
                FlowContentModel.objects.create(name=content4, type_id=titles4.id)

            flow = FlowModel.objects.filter(name=flows).first()
            HistoryModel.objects.create(users_id=self._cuser.id, flows_id=flow.id,is_status=1)
            history = HistoryModel.objects.filter(users_id=self._cuser.id, flows_id=flow.id, is_status=1).first()
            nodes = FlowNodeModel.objects.filter(flows_id=flow.id, nodes=None).first()
            stations = StationModel.objects.filter(id=nodes.stations_id).first()
            ApprovalModel.objects.create(historys_id=history.id, nodes_id=nodes.id, stations_id=stations.id, is_status=1)

            return Response({'code':status.HTTP_200_OK,'msg':'申请流程成功'})

        except Exception as e:
            print(str(e))
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':'服务器错误'})

# 流程实例管理
class ApprovalView(ViewSet):

    @jwt_auth
    # 审批该流程节点 同意
    def approval_consent(self, request, pk):
        cause = request.data.get('cause')
        try:
            ApprovalModel.objects.filter(id=pk).update(is_status=3,cause=cause)

            approval = ApprovalModel.objects.filter(id=pk).first()
            node = FlowNodeModel.objects.filter(id=approval.nodes_id).first()
            nodes = FlowNodeModel.objects.filter(nodes=node.id).first()
            history = HistoryModel.objects.filter(id=approval.historys_id).first()

            # 判断节点实例数量是否和节点数量一致
            flow = FlowNodeModel.objects.filter(flows_id=history.flows_id).count()
            approval = ApprovalModel.objects.filter(historys_id=history.id).count()

            if flow > approval:
                ApprovalModel.objects.create(historys_id=history.id,nodes_id=nodes.id,stations_id=nodes.stations_id,is_status=2)

            app = ApprovalModel.objects.filter(historys_id=history.id).all()
            app = ApprovalSer(app, many=True)
            app = json.loads(json.dumps(app.data))
            lst = []
            for i in app:
                lst.append(i['is_status'])
                k = 0
                for j in lst:
                    if j == '已同意':
                        k += 1
                    if k == flow:
                        HistoryModel.objects.filter(id=i['historys']).update(is_status=2)

            return Response({'code':status.HTTP_200_OK,'msg':'审批成功'})
        except Exception as e:
            print(str(e))
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':'服务器错误'})

    @jwt_auth
    # 审批该流程节点 不同意
    def approval_dissent(self, request, pk):
        cause = request.data.get('cause')
        try:
            ApprovalModel.objects.filter(id=pk).update(is_status=4, cause=cause)

            approval = ApprovalModel.objects.filter(id=pk).first()
            HistoryModel.objects.filter(id=approval.historys_id).update(is_status=3)
            return Response({'code':status.HTTP_200_OK,'msg':'审批成功'})
        except Exception as e:
            print(str(e))
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':'服务器错误'})
